using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using NSMBe4;
using SDAT;
using LibNDSFormats.NSBMD;

namespace MKDS_Course_Editor
{
    public partial class Form1 : Form
    {
        Players.MusicPlayer midi = new Players.MusicPlayer();
        public Process nsbmd = new Process();
        public IntPtr handle2 = new IntPtr(0);
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
        public TreeView tree;
        #region Methods/Consts for Embedding a Window
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = true,
             CallingConvention = CallingConvention.StdCall)]
        private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
        private static extern long GetWindowLong(IntPtr hwnd, int nIndex);

        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        private static extern bool PostMessage(IntPtr hwnd, uint Msg, int wParam, int lParam);
        [DllImport("USER32.DLL")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        public abstract class WindowStyles
        {
            public const uint WS_OVERLAPPED = 0x00000000;
            public const uint WS_POPUP = 0x80000000;
            public const uint WS_CHILD = 0x40000000;
            public const uint WS_MINIMIZE = 0x20000000;
            public const uint WS_VISIBLE = 0x10000000;
            public const uint WS_DISABLED = 0x08000000;
            public const uint WS_CLIPSIBLINGS = 0x04000000;
            public const uint WS_CLIPCHILDREN = 0x02000000;
            public const uint WS_MAXIMIZE = 0x01000000;
            public const uint WS_CAPTION = 0x00C00000;     /* WS_BORDER | WS_DLGFRAME  */
            public const uint WS_BORDER = 0x00800000;
            public const uint WS_DLGFRAME = 0x00400000;
            public const uint WS_VSCROLL = 0x00200000;
            public const uint WS_HSCROLL = 0x00100000;
            public const uint WS_SYSMENU = 0x00080000;
            public const uint WS_THICKFRAME = 0x00040000;
            public const uint WS_GROUP = 0x00020000;
            public const uint WS_TABSTOP = 0x00010000;

            public const uint WS_MINIMIZEBOX = 0x00020000;
            public const uint WS_MAXIMIZEBOX = 0x00010000;



            public const uint WS_TILED = WS_OVERLAPPED;
            public const uint WS_ICONIC = WS_MINIMIZE;
            public const uint WS_SIZEBOX = WS_THICKFRAME;
            public const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;

            // Common Window Styles

            public const uint WS_OVERLAPPEDWINDOW =
                (WS_OVERLAPPED |
                  WS_CAPTION |
                  WS_SYSMENU |
                  WS_THICKFRAME |
                  WS_MINIMIZEBOX |
                  WS_MAXIMIZEBOX);

            public const uint WS_POPUPWINDOW =
                (WS_POPUP |
                  WS_BORDER |
                  WS_SYSMENU);

            public const uint WS_CHILDWINDOW = WS_CHILD;

            //Extended Window Styles

            public const uint WS_EX_DLGMODALFRAME = 0x00000001;
            public const uint WS_EX_NOPARENTNOTIFY = 0x00000004;
            public const uint WS_EX_TOPMOST = 0x00000008;
            public const uint WS_EX_ACCEPTFILES = 0x00000010;
            public const uint WS_EX_TRANSPARENT = 0x00000020;

            //#if(WINVER >= 0x0400)
            public const uint WS_EX_MDICHILD = 0x00000040;
            public const uint WS_EX_TOOLWINDOW = 0x00000080;
            public const uint WS_EX_WINDOWEDGE = 0x00000100;
            public const uint WS_EX_CLIENTEDGE = 0x00000200;
            public const uint WS_EX_CONTEXTHELP = 0x00000400;

            public const uint WS_EX_RIGHT = 0x00001000;
            public const uint WS_EX_LEFT = 0x00000000;
            public const uint WS_EX_RTLREADING = 0x00002000;
            public const uint WS_EX_LTRREADING = 0x00000000;
            public const uint WS_EX_LEFTSCROLLBAR = 0x00004000;
            public const uint WS_EX_RIGHTSCROLLBAR = 0x00000000;

            public const uint WS_EX_CONTROLPARENT = 0x00010000;
            public const uint WS_EX_STATICEDGE = 0x00020000;
            public const uint WS_EX_APPWINDOW = 0x00040000;



            public const uint WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
            public const uint WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
            //#endif /* WINVER >= 0x0400 */

            //#if(_WIN32_WINNT >= 0x0500)
            public const uint WS_EX_LAYERED = 0x00080000;
            //#endif /* _WIN32_WINNT >= 0x0500 */

            //#if(WINVER >= 0x0500)
            public const uint WS_EX_NOINHERITLAYOUT = 0x00100000; // Disable inheritence of mirroring by children
            public const uint WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
            //#endif /* WINVER >= 0x0500 */

            //#if(_WIN32_WINNT >= 0x0500)
            public const uint WS_EX_COMPOSITED = 0x02000000;
            public const uint WS_EX_NOACTIVATE = 0x08000000;
            //#endif /* _WIN32_WINNT >= 0x0500 */
        }




        private const int SWP_NOOWNERZORDER = 0x200;
        private const int SWP_NOREDRAW = 0x8;
        private const int SWP_NOZORDER = 0x4;
        private const int SWP_SHOWWINDOW = 0x0040;
        private const int WS_EX_MDICHILD = 0x40;
        private const int SWP_FRAMECHANGED = 0x20;
        private const int SWP_NOACTIVATE = 0x10;
        private const int SWP_ASYNCWINDOWPOS = 0x4000;
        private const int SWP_NOMOVE = 0x2;
        private const int SWP_NOSIZE = 0x1;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 0x10000000;
        private const int WM_CLOSE = 0x10;
        private const int WS_CHILD = 0x40000000;
        private const int WS_MAXIMIZE = 3;
        #endregion
        #region Variables
        private Panel gpsPanel;
        private IntPtr gpsHandle;
        private Process gpsProcess = null;
        private ProcessStartInfo gpsPSI = new ProcessStartInfo();
        #endregion
        public string args = "";
        public string path = "";
        public string path2 = "";
        public Tinke.PluginHost pluginHost = new Tinke.PluginHost();
        public string ncgr = "";
        public string nclr = "";
        public string nscr = "";
        public string narn = "";
        public string ncer = "";
        public string bncl = "";
        public string dirpath = "";
        public System.Diagnostics.Process p = new System.Diagnostics.Process();
        public short useNDSfileID1;
        public short useNDSfileID2;
        public nds_rom dialog;
        public Form1(string args2)
        {
            args = args2;
            InitializeComponent();
        }
        public void doAction(byte[] file, string name,ushort fileID)
        {
            treeView1.Nodes.Clear();
            switch (Path.GetExtension(name).ToLower())
            {
                case ".nclr":
                    PluginInterface.NCLR c = Tinke.Imagen_NCLR.Leer(file);
                    Tinke.iNCLR iNCLR1 = new Tinke.iNCLR(c);
                    panel1.Controls.Clear();
                    panel1.Controls.Add(iNCLR1);
                    panel1.Show();
                    panel1.Visible = true;
                    break;
                case ".carc":
                    path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                    System.IO.Directory.CreateDirectory(path);
                    File.WriteAllBytes(path +"\\"+ name, file);
                    File.WriteAllBytes(path + "\\" + name.Replace("carc", "NARC"), NSMBe4.ROM.LZ77_Decompress(File.ReadAllBytes(path +"\\"+ name)));
                    //lz.Decompress(path +"\\"+ name, path);
                    System.IO.Directory.CreateDirectory(path + "\\" + "unpack");
                    narc.unpack(path + "\\" + name.Replace("carc", "NARC"), path + "\\" + "unpack");
                    dirpath = path;
                    string[] en = System.IO.Directory.GetFileSystemEntries(path + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                    for (int i = 0; i < en.Length; i++)
                    {
                        en[i] = en[i].Replace(path + "\\" + "unpack", "");
                    }
                    PopulateTreeView(treeView1, en, '\\');
                    TreeNodeCollection nc3 = treeView1.Nodes[0].Nodes;
                    treeView1.Nodes.Clear();
                    TreeNode[] tr = new TreeNode[nc3.Count];
                    nc3.CopyTo(tr, 0);
                    treeView1.Nodes.AddRange(tr);
                    foreach (TreeNode rootNode in treeView1.Nodes)
                        ParseNode(rootNode, 1);
                    useNDSfileID1 = (short)fileID;
                    break;
                case ".narc":
                    path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                    System.IO.Directory.CreateDirectory(path);
                    File.WriteAllBytes(path + "\\" + name, file);
                    System.IO.Directory.CreateDirectory(path + "\\" + "unpack");
                    narc.unpack(path + "\\" + name, path + "\\" + "unpack");
                    dirpath = path;
                    string[] en_ = System.IO.Directory.GetFileSystemEntries(path + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                    for (int i = 0; i < en_.Length; i++)
                    {
                        en_[i] = en_[i].Replace(path + "\\" + "unpack", "");
                    }
                    PopulateTreeView(treeView1, en_, '\\');
                    TreeNodeCollection nc3_ = treeView1.Nodes[0].Nodes;
                    treeView1.Nodes.Clear();
                    TreeNode[] tr_ = new TreeNode[nc3_.Count];
                    nc3_.CopyTo(tr_, 0);
                    treeView1.Nodes.AddRange(tr_);
                    foreach (TreeNode rootNode in treeView1.Nodes)
                        ParseNode(rootNode, 1);
                    useNDSfileID1 = (short)fileID;
                    break;
            }
        }
        public void doAction(byte[] file1, byte[] file2, string name1, string name2)
        {
            switch (Path.GetExtension(name1).ToLower())
            {
                case ".ncgr":
                    PluginInterface.NCGR q = Tinke.Imagen_NCGR.Leer(file1);
                    PluginInterface.NCLR z = Tinke.Imagen_NCLR.Leer(file2);

                    Tinke.iNCGR iNCGR2 = new Tinke.iNCGR(q, z);
                    panel1.Controls.Clear();
                    panel1.Controls.Add(iNCGR2);
                    break;
            }
        }
        public void doAction(byte[] file1, byte[] file2, byte[] file3, string name1, string name2, string name3)
        {
            switch (Path.GetExtension(name1).ToLower())
            {
                case ".ncer":
                    PluginInterface.NCER q2 = Tinke.Imagen_NCER.Leer(file1);
                    PluginInterface.NCGR q = Tinke.Imagen_NCGR.Leer(file2);
                    PluginInterface.NCLR z = Tinke.Imagen_NCLR.Leer(file3);

                    Tinke.iNCER iNCER2 = new Tinke.iNCER(q2,q, z);
                    panel1.Controls.Clear();
                    panel1.Controls.Add(iNCER2);
                    break;
                case ".nscr":
                    PluginInterface.NCGR w = Tinke.Imagen_NCGR.Leer(file2);
                    PluginInterface.NCLR qr = Tinke.Imagen_NCLR.Leer(file3);
                    PluginInterface.NSCR p2 = Tinke.Imagen_NSCR.Leer(file1);
                    w.rahc.tileData = Tinke.Imagen_NSCR.Modificar_Tile(p2, w.rahc.tileData);
                    w.rahc.nTilesX = (ushort)(p2.section.width / 8);
                    w.rahc.nTilesY = (ushort)(p2.section.height / 8);
                    Tinke.iNCGR iNCGR3 = new Tinke.iNCGR(w, qr);
                    panel1.Controls.Clear();
                    panel1.Controls.Add(iNCGR3);
                    break;
            }
        }
        public void doAction(byte[] file1, byte[] file2, byte[] file3, byte[] file4, string name1, string name2, string name3, string name4)
        {
            switch (Path.GetExtension(name1).ToLower())
            {
                case ".nanr":
                    PluginInterface.NANR q2_ = Tinke.Imagen_NANR.Leer(file1);
                    PluginInterface.NCER q2 = Tinke.Imagen_NCER.Leer(file2);
                    PluginInterface.NCGR q_ = Tinke.Imagen_NCGR.Leer(file3);
                    PluginInterface.NCLR z_ = Tinke.Imagen_NCLR.Leer(file4);

                    Tinke.iNANR iNANR2 = new Tinke.iNANR(z_, q_,q2, q2_);
                    panel1.Controls.Clear();
                    panel1.Controls.Add(iNANR2);
                    break;
            }
        }
        public void doAction(byte[] file, string name, bool second, ushort fileID)
        {
            treeView2.Nodes.Clear();
            switch (Path.GetExtension(name).ToLower())
            {
                case ".carc":
                    path2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                    System.IO.Directory.CreateDirectory(path2);
                    File.WriteAllBytes(path2 + "\\" + name, file);
                    File.WriteAllBytes(path2 + "\\" + name.Replace("carc", "NARC"), NSMBe4.ROM.LZ77_Decompress(File.ReadAllBytes(path2 + "\\" + name)));
                    //lz.Decompress(path2 + "\\" + name, path2);
                    System.IO.Directory.CreateDirectory(path2 + "\\" + "unpack");
                    narc.unpack(path2 + "\\" + name.Replace("carc", "NARC"), path2 + "\\unpack");
                    string[] en = System.IO.Directory.GetFileSystemEntries(path2 + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                    for (int i = 0; i < en.Length; i++)
                    {
                        en[i] = en[i].Replace(path2 + "\\" + "unpack", "");
                    }
                    PopulateTreeView(treeView2, en, '\\');
                    TreeNodeCollection nc3 = treeView2.Nodes[0].Nodes;
                    treeView2.Nodes.Clear();
                    TreeNode[] tr = new TreeNode[nc3.Count];
                    nc3.CopyTo(tr, 0);
                    treeView2.Nodes.AddRange(tr);
                    foreach (TreeNode rootNode in treeView2.Nodes)
                        ParseNode(rootNode, 2);
                    useNDSfileID2 = (short)fileID;
                    break;
                case ".narc":
                    path2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                    System.IO.Directory.CreateDirectory(path2);
                    File.WriteAllBytes(path2 + "\\" + name, file);
                    System.IO.Directory.CreateDirectory(path2 + "\\" + "unpack");
                    narc.unpack(path2 + "\\" + name, path2 + "\\unpack");
                    string[] en2 = System.IO.Directory.GetFileSystemEntries(path2 + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                    for (int i = 0; i < en2.Length; i++)
                    {
                        en2[i] = en2[i].Replace(path2 + "\\" + "unpack", "");
                    }
                    PopulateTreeView(treeView1, en2, '\\');
                    TreeNodeCollection nc4 = treeView1.Nodes[0].Nodes;
                    treeView1.Nodes.Clear();
                    TreeNode[] tr1 = new TreeNode[nc4.Count];
                    nc4.CopyTo(tr1, 0);
                    treeView1.Nodes.AddRange(tr1);
                    foreach (TreeNode rootNode in treeView1.Nodes)
                        ParseNode(rootNode, 2);
                    useNDSfileID2 = (short)fileID;
                    break;
            }
        }
		narc.directory Narc1 = null;
		narc.directory Narc2 = null;
        public Form1()
        {
            InitializeComponent();
            imageList1.Images.Clear();
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.page_white);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.image);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.map);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.folder);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.image_animated);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.nkm);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.kcl);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.palette);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.picture);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.images);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.pictures);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.film_link);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.package);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.package_green);
            imageList1.Images.Add(MKDS_Course_Editor.Properties.Resources.music);
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog1.FileName.Length > 0)
            {

                treeView1.Nodes.Clear();
                useNDSfileID1 = -1;
                useNDSfileID2 = -1;
                switch (openFileDialog1.SafeFileName.Remove(0, openFileDialog1.SafeFileName.LastIndexOf(".")).ToLower())
                {
                    case ".carc":
                        path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                        System.IO.Directory.CreateDirectory(path);
                        File.WriteAllBytes(path + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"), NSMBe4.ROM.LZ77_Decompress(File.ReadAllBytes(openFileDialog1.FileName)));
                        //lz.Decompress(openFileDialog1.FileName, path);
                        System.IO.Directory.CreateDirectory(path + "\\" + "unpack");
                        Narc1 = narc.unpack(path + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"), path + "\\" + "unpack");
						//narc.pack(root, @"C:\test.narc");
                        dirpath = path;
						treeView1.Nodes.AddRange(Narc1.getNodes(contextMenuStrip2, contextMenuStrip3));
                        /*string[] en = System.IO.Directory.GetFileSystemEntries(path + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                        for (int i = 0; i < en.Length; i++)
                        {
                            en[i] = en[i].Replace(path + "\\" + "unpack", "");
                        }
                        PopulateTreeView(treeView1, en, '\\');
                        TreeNodeCollection nc3 = treeView1.Nodes[0].Nodes;
                        treeView1.Nodes.Clear();
                        TreeNode[] tr = new TreeNode[nc3.Count];
                        nc3.CopyTo(tr, 0);
                        treeView1.Nodes.AddRange(tr);
                        foreach (TreeNode rootNode in treeView1.Nodes)
                            ParseNode(rootNode, 1);*/
                        break;
                    case ".narc":
                        path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                        System.IO.Directory.CreateDirectory(path);
                        System.IO.Directory.CreateDirectory(path + "\\" + "unpack");
                        System.IO.File.Copy(openFileDialog1.FileName, path + "\\" + openFileDialog1.SafeFileName);
						Narc1 = narc.unpack(path + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"), path + "\\" + "unpack");
                        dirpath = path;
						treeView1.Nodes.AddRange(Narc1.getNodes(contextMenuStrip2, contextMenuStrip3));
                       /* string[] en_ = System.IO.Directory.GetFileSystemEntries(path + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                        for (int i = 0; i < en_.Length; i++)
                        {
                            en_[i] = en_[i].Replace(path + "\\" + "unpack", "");
                        }
                        PopulateTreeView(treeView1, en_, '\\');
                        TreeNodeCollection nc3_ = treeView1.Nodes[0].Nodes;
                        treeView1.Nodes.Clear();
                        TreeNode[] tr_ = new TreeNode[nc3_.Count];
                        nc3_.CopyTo(tr_, 0);
                        treeView1.Nodes.AddRange(tr_);
                        foreach (TreeNode rootNode in treeView1.Nodes)
                            ParseNode(rootNode,1);*/
                        break;
                    case ".nkm":
                        Form f = new nkm(openFileDialog1.FileName);
                        f.ShowDialog();
                        break;
                    case ".swav":
                        Form fq = new swav(openFileDialog1.FileName);
                        fq.ShowDialog();
                        break;
                    case ".swar":
                        Form fq2 = new swar(openFileDialog1.FileName);
                        fq2.ShowDialog();
                        break;
                    case ".strm":
                        Form fq22 = new strm(openFileDialog1.FileName);
                        fq22.ShowDialog();
                        break;
                    case ".kcl":
                        if (libWiiSharp.Lz77.IsLz77Compressed(openFileDialog1.FileName))
                        {
                            libWiiSharp.Lz77 lz2 = new libWiiSharp.Lz77();
                            byte[] f9 = lz2.Decompress(System.IO.File.ReadAllBytes(openFileDialog1.FileName));
                            Stream str = new MemoryStream(f9);


                            Form f2 = new kcl(str, true);
                            f2.ShowDialog();
                        }
                        else
                        {
                            Form f2 = new kcl(openFileDialog1.FileName);
                            f2.ShowDialog();
                        }
                        break;
                    case ".nds":
                        nds_rom nd = new nds_rom(openFileDialog1.FileName, this, midi);
                        dialog = nd;
                        nd.Show(this);
                        break;
                    case ".nsbmd":
                        //panel1.Controls.Clear();
                        Form nsbm = new nsbmd(openFileDialog1.FileName);
                        //nsbm.TopLevel = false;
                        //nsbm.Parent = this;
                        //nsbm.Dock = DockStyle.Fill;
                        //nsbm.FormBorderStyle = FormBorderStyle.None;
                        //panel1.Controls.Add(nsbm);
                        //nsbm.Show();
                        nsbm.ShowDialog();
                        break;
                    case ".nsbtx":
                        if (System.IO.File.Exists(openFileDialog1.FileName.Replace("nsbtx", "nsbtp")))
                        {
                            Form f3 = new MKDS_Course_Editor.NSBTX.nsbtx_(openFileDialog1.FileName, true);
                            f3.ShowDialog();
                        }
                        else
                        {
                            Form f3 = new MKDS_Course_Editor.NSBTX.nsbtx_(openFileDialog1.FileName, false);
                            f3.ShowDialog();
                        }
                        break;
                    case ".nsbtp":
                        if (System.IO.File.Exists(openFileDialog1.FileName.Replace(".nsbtp", ".nsbtx")))
                        {
                            Form f3 = new nsbtx_(openFileDialog1.FileName.Replace(".nsbtp", ".nsbtx"), true);
                            f3.ShowDialog();
                        }
                        else if (System.IO.File.Exists(openFileDialog1.FileName.Replace(".nsbtp", ".nsbmd")))
                        {
                            Form f3 = new nsbtx_(openFileDialog1.FileName.Replace(".nsbtp", ".nsbmd"), true);
                            f3.ShowDialog();
                        }
                        break;
                    case ".bin":
                        {
                            if (openFileDialog1.SafeFileName.EndsWith("icl.bin") || openFileDialog1.SafeFileName.EndsWith("ncl.bin"))
                            {
                                Stream fs = File.OpenRead(openFileDialog1.FileName);
                                byte[] byt;
                                Color[] clr;
                                //if (openFileDialog1.SafeFileName.EndsWith("ncl.bin"))
                                //{
                                //PuyoTools.LZSS lz3 = new PuyoTools.LZSS();
                                //lz3.Decompress(ref fs);
                                //fs.Read(byt, 0, (int)fs.Length);
                                //clr = Tinke.Convertir.BGR555(byt);
                                //}
                                //else
                                //{
                                clr = Tinke.Convertir.BGR555(File.ReadAllBytes(openFileDialog1.FileName));
                                // }
                                if (clr[0] == Color.Black && clr[1] == Color.Black && clr[2] == Color.Black && clr[3] == Color.Black)
                                {
                                    PuyoTools.LZSS lz3 = new PuyoTools.LZSS();
                                    lz3.Decompress(ref fs);
                                    byt = new byte[fs.Length];
                                    fs.Read(byt, 0, (int)fs.Length);

                                    clr = Tinke.Convertir.BGR555(byt);

                                }

                                Bitmap bmp = new Bitmap(160, 160, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                                bool fin = false;

                                for (int i = 0; i < 16 & !fin; i++)
                                {
                                    for (int j = 0; j < 16; j++)
                                    {
                                        if (clr.Length == j + 16 * i)
                                        {
                                            fin = true;
                                            break;
                                        }

                                        for (int k = 0; k < 10; k++)
                                            for (int q = 0; q < 10; q++)
                                                bmp.SetPixel(j * 10 + q, i * 10 + k,
                                                    clr[j + 16 * i]);
                                    }
                                }


                                PictureBox pic = new PictureBox();
                                pic.SizeMode = PictureBoxSizeMode.AutoSize;
                                pic.Image = bmp;
                                panel1.Controls.Clear();
                                panel1.Controls.Add(pic);
                            }
                            else if (openFileDialog1.SafeFileName.EndsWith("ncg.bin") || openFileDialog1.SafeFileName.EndsWith("icg.bin"))
                            {
                                string s3 = openFileDialog1.FileName;
                                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                                    && openFileDialog1.FileName.Length > 0)
                                {
                                    string s2 = openFileDialog1.FileName;
                                    Pictures.Picture c = new Pictures.Picture(s3, s2, UI.GraphicsControl.GraphicsType.Raw);
                                    c.ShowDialog();
                                }
                            }
                            else if (openFileDialog1.SafeFileName.EndsWith("LZ.bin"))
                            {
                                byte[] byt = NSMBe4.ROM.LZ77_Decompress(File.ReadAllBytes(openFileDialog1.FileName));
                                try
                                {
                                    if (byt[0] == Convert.ToByte('B') && byt[1] == Convert.ToByte('M') && byt[2] == Convert.ToByte('D') && byt[3] == Convert.ToByte('0'))
                                    {
                                        File.WriteAllBytes(openFileDialog1.SafeFileName, byt);
                                        Form nsbm2 = new nsbmd(openFileDialog1.SafeFileName);
                                        nsbm2.ShowDialog();
                                        File.Delete(openFileDialog1.SafeFileName);
                                    }
                                }
                                catch { }
                            }
                            else if (openFileDialog1.SafeFileName == "staff_ghost_time.bin")
                            {
                                Form fo = new StaffGhostTime(openFileDialog1.FileName);
                                fo.ShowDialog();
                            }
                            else if (openFileDialog1.SafeFileName == "kartoffsetdata.bin")
                            {
                                Form fo = new kartoffsetdata.kartoffsetdata(openFileDialog1.FileName);
                                fo.ShowDialog();
                            }
                            else if (openFileDialog1.SafeFileName.EndsWith("nsc.bin") || openFileDialog1.SafeFileName.EndsWith("isc.bin"))
                            {
                                string s3 = openFileDialog1.FileName;
                                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                                    && openFileDialog1.FileName.Length > 0)
                                {
                                    string s2 = openFileDialog1.FileName;
                                    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                                   && openFileDialog1.FileName.Length > 0)
                                    {
                                        string s4 = openFileDialog1.FileName;
                                        Pictures.Picture c = new Pictures.Picture(s2, s4, UI.GraphicsControl.GraphicsType.Raw, s3);
                                        c.ShowDialog();
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    byte[] byt = File.ReadAllBytes(openFileDialog1.FileName);
                                    if (byt[0] == Convert.ToByte('T') && byt[1] == Convert.ToByte('E') && byt[2] == Convert.ToByte('X') && byt[3] == Convert.ToByte('S')/* || byt[0] == Convert.ToByte('H') && byt[1] == Convert.ToByte('B') && byt[2] == Convert.ToByte('D') && byt[3] == Convert.ToByte('F')*/)
                                    {
                                        Form f2 = new TEXS_(openFileDialog1.FileName);
                                        f2.ShowDialog();
                                    }
                                    else if (byt[8] == Convert.ToByte('M') && byt[9] == Convert.ToByte('D') && byt[10] == Convert.ToByte('L') && byt[11] == Convert.ToByte('F'))
                                    {
                                        HBDF_MDLF b = new HBDF_MDLF(openFileDialog1.FileName);
                                        b.ShowDialog();
                                    }
                                }
                                catch { }
                            }
                            break;
                        }
                    case ".sdat":
                       Form fq3 = new sdat_(File.ReadAllBytes(openFileDialog1.FileName), Path.GetFileName(openFileDialog1.FileName), midi);
                        fq3.ShowDialog();
                        break;
					case ".thp":
						GCN.THP.THPPlayer play = new GCN.THP.THPPlayer(openFileDialog1.FileName);
						play.ShowDialog();
						break;
                    case ".bmd":
                        Form bm = new bmd_view(openFileDialog1.FileName);
                        bm.ShowDialog();
                        break;
                    case ".bti":
                        MKDS_Course_Editor.GCN.BTI.BTI btii = new GCN.BTI.BTI(openFileDialog1.FileName);
                        btii.ShowDialog();
                        break;
                    case ".tpl":
                        MKDS_Course_Editor.WII.TPL.TPL tpll = new WII.TPL.TPL(openFileDialog1.FileName);
                        tpll.ShowDialog();
                        break;
                    case ".bmg":
                        Form b3 = new bmg(openFileDialog1.FileName);
                        b3.ShowDialog();
                        break;
                    case ".obj":
                        //Form fw = new obj(openFileDialog1.FileName);
                        //MTV3D65.TVScene sc = new MTV3D65.TVScene();
                        //MTV3D65.TVMesh mes= TreeGenerator.OBJImporter.getMesh(sc, openFileDialog1.FileName, "mesh");
                        //kcl.GenerateKCL(openFileDialog1.FileName.Replace(".obj", "_.kcl"), openFileDialog1.FileName);
                        //fw.ShowDialog();
                        break;
                    case ".nsbta":
                        NSBTA.NSBTA.NSBTA_File t = NSBTA.NSBTA.Read(openFileDialog1.FileName);
                        break;
                    case ".sseq":
                        sseq s = new sseq(openFileDialog1.FileName, midi);
                        s.ShowDialog();
                        File.Delete(openFileDialog1.FileName);
                        File.Create(openFileDialog1.FileName).Close();
                        File.WriteAllBytes(openFileDialog1.FileName, s.getBytes());
                        break;
                    case ".3dxml":


                        break;
                    case ".spa":
                        spa sp = new spa(openFileDialog1.FileName);
                        sp.ShowDialog();
                        break;
                    case ".baa":
                        GCN.Sound.BAA bb = new GCN.Sound.BAA(openFileDialog1.FileName);
                        bb.ShowDialog();
                        break;
                    case ".nclr":
                        {
                            PluginInterface.NCLR c = Tinke.Imagen_NCLR.Leer(openFileDialog1.FileName);
                            List<Color> c3 = new List<Color>();
                            for (int i = 0; i < c.pltt.paletas.Length; i++)
                            {
                                c3.AddRange(c.pltt.paletas[i].colores);
                            }
                            Form nc = new MKDS_Course_Editor.nclr_e(c3.ToArray(), c.pltt.profundidad == ColorDepth.Depth8Bit ? true : false, c.pltt.unknown1);
                            nc.ShowDialog();
                            break;
                        }
                }
            }
        }
        private Bitmap RenderBackground(byte[] GFXFile, byte[] Palette2, byte[] LayoutFile, int TileOffset)
        {
            bool sm64 = false;
            if (MessageBox.Show("Is sm64ds map?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                sm64 = true;
            }
            else
            {
                sm64 = false;
            }
            int FilePos;

            byte[] ePalFile;
            // First get the palette out
            if (!sm64)
            {
                ePalFile = ROM.LZ77_Decompress(Palette2);
            }
            else
            {
                ePalFile = Palette2;
            }

            Color[] Palette = new Color[512];

            Color[] Palette3 = Tinke.Convertir.BGR555(ePalFile);
            Array.Copy(Palette3, 0, Palette, 0, Palette3.Length);

            Palette[0] = Color.Transparent;
            Palette[256] = Color.Transparent;

            // Load graphics
            byte[] eGFXFile;

            //if (!sm64)
            //{
            eGFXFile = ROM.LZ77_Decompress(GFXFile);
            //}
            //else
            //{
            // eGFXFile = GFXFile;
            //}
            bool use4bpp = true;
            int TileCount = eGFXFile.Length / (use4bpp ? 32 : 64);
            Bitmap TilesetBuffer = new Bitmap(TileCount * 8, 16);

            FilePos = 0;
           // for (int TileIdx = 0; TileIdx < TileCount; TileIdx++)
           // {
           //     int TileSrcX = TileIdx * 8;
           //     for (int TileY = 0; TileY < 8; TileY++)
           //     {
           //         for (int TileX = 0; TileX < 8; TileX++)
           //         {
           //             TilesetBuffer.SetPixel(TileSrcX + TileX, TileY, Palette[eGFXFile[FilePos]]);
           //             TilesetBuffer.SetPixel(TileSrcX + TileX, TileY + 8, Palette[eGFXFile[FilePos] + 256]);
            //            FilePos++;
            //        }
           //     }
           // }
           
            for (int i = 0; i < TileCount; i++)
            {
                for (int TileY = 0; TileY < 8; TileY++)
                {
                    for (int TileX = 0; TileX < (use4bpp ? 4 : 8); TileX++)
                    {
                        if (use4bpp)
                        {
                            TilesetBuffer.SetPixel(i * 8 + TileX * 2 + 1, TileY, Palette[eGFXFile[FilePos] / 16 + (int)0 * 16]);
                            TilesetBuffer.SetPixel(i * 8 + TileX * 2, TileY, Palette[eGFXFile[FilePos] % 16 + (int)0 * 16]);
                        }
                        else
                            TilesetBuffer.SetPixel(i * 8 + TileX, TileY, Palette[eGFXFile[FilePos] + (int)0 * 16]);
                        FilePos++;
                    }
                }
            }

            // Load layout
            byte[] eLayoutFile = LayoutFile;
            int LayoutCount = eLayoutFile.Length / 2;
            Bitmap BG = new Bitmap(256, 256, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics BGGraphics = Graphics.FromImage(BG);
            BGGraphics.Clear(Color.Transparent);

            FilePos = 0;
            int TileNum;
            byte ControlByte;
            Rectangle SrcRect;
            int SrcX = 0;
            int SrcY = 0;
            Bitmap fliptile = new Bitmap(8, 8);
            Graphics g = Graphics.FromImage(fliptile);
            for (int TileIdx = 0; TileIdx < LayoutCount; TileIdx++)
            {
                TileNum = eLayoutFile[FilePos];
                ControlByte = eLayoutFile[FilePos + 1];
                TileNum |= (ControlByte & 3) << 8;
                TileNum -= TileOffset;
                SrcRect = new Rectangle(TileNum * 8, (ControlByte & 16) != 0 ? 8 : 0, 8, 8);
                if ((ControlByte & 4) != 0 || (ControlByte & 8) != 0)
                {
                    g.DrawImage(TilesetBuffer, 0, 0, SrcRect, GraphicsUnit.Pixel);
                    if ((ControlByte & 4) != 0)
                        fliptile.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    if ((ControlByte & 8) != 0)
                        fliptile.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    BGGraphics.DrawImage(fliptile, SrcX, SrcY);
                }
                else
                {
                    BGGraphics.DrawImage(TilesetBuffer, SrcX, SrcY, SrcRect, GraphicsUnit.Pixel);
                }
                SrcX += 8;
                if (SrcX >= 512) { SrcX = 0; SrcY += 8; }
                FilePos += 2;
            }

            return BG;

        }

        Color InvertAColor(Color aColor)
        {
            
            return Color.FromArgb(aColor.R, aColor.G, aColor.B);

        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
        private Color gpalette(int n, Color[] pal)
        {
            if (n >= pal.Length)
                return Color.Pink;
            return pal[n];
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                TreeView t = (TreeView)sender;
                t.SelectedNode = e.Node;
                tree = t;
            }
            else
            {
                if (sender == treeView1)
                {
                    dirpath = path;
                }
                else { dirpath = path2; }
                if (e.Node.Text.Contains("."))
                {
                    switch (e.Node.Text.Remove(0, e.Node.Text.LastIndexOf(".")).ToLower())
                    {
                        case ".nsbtx":
                            break;
                        case ".nsbmd":
                            break;
                        case ".nsbtp":
                        case ".nsbta":
                            break;
                        case ".nkm":
                            break;
                        case ".kcl":
                            break;
                        case ".nclr":
                            nclr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            break;
                        case ".ncgr":
                            ncgr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            break;
                        case ".nscr":
                            nscr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            break;
                        case ".ncer":
                            ncer = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            break;
                        case ".nanr":
                            narn = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            break;
                    }
                }
            }
        }
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (sender == treeView1)
            {
                dirpath = path;
            }
            else { dirpath = path2; }
            if (e.Node.Text.Contains("."))
            {

                Process[] nsbmd2 = Process.GetProcessesByName("nsbmd");
                for (int i = 0; i < nsbmd2.Length; i++)
                {
                    nsbmd2[i].Kill();
                }
                handle2 = IntPtr.Zero;
                nsbmd2 = null;
                switch (e.Node.Text.Remove(0, e.Node.Text.LastIndexOf(".")).ToLower())
                {

                    case ".bmd":
                        Form bm = new bmd_view(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                        bm.ShowDialog();
                        break;
                    case ".nsbtx":
                            if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtx", "nsbtp")))
                            {
                                Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath, true);
                                f.ShowDialog();
                            }
                            else
                            {
                                Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath, false);
                                f.ShowDialog();
                            }
                        break;
                    case ".nsbmd":
                        if (e.Node.ForeColor == Color.Blue)
                        {
                            byte[] b = new libWiiSharp.Lz77().Decompress(File.ReadAllBytes(dirpath + "\\" + "unpack\\" + e.Node.FullPath));
                            Form nsbm = new nsbmd(b);
                            nsbm.ShowDialog();
                        }
                        else
                        {
                            if (sender == treeView1)
                            {
                                if (File.Exists(path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx")))
                                {
                                    Form nsbm = new nsbmd(File.ReadAllBytes(dirpath + "\\" + "unpack\\" + e.Node.FullPath), File.ReadAllBytes(path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx")), dirpath + "\\" + "unpack\\" + e.Node.FullPath, path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx"));
                                    nsbm.ShowDialog();
                                }
                                else
                                {
                                    Form nsbm = new nsbmd(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                                    nsbm.ShowDialog();
                                }
                            }
                            else
                            {
                                if (File.Exists(path + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx")))
                                {
                                    Form nsbm = new nsbmd(File.ReadAllBytes(dirpath + "\\" + "unpack\\" + e.Node.FullPath), File.ReadAllBytes(path + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx")), dirpath + "\\" + "unpack\\" + e.Node.FullPath, path + "\\" + "unpack\\" + e.Node.FullPath.Replace(".nsbmd", ".nsbtx"));
                                    nsbm.ShowDialog();
                                }
                                else
                                {
                                    Form nsbm = new nsbmd(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                                    nsbm.ShowDialog();
                                }
                            }
                            
                        }
                        break;
                    case ".nsbtp":
                        if (sender == treeView1)
                        {
                            if (System.IO.File.Exists(path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd")))
                            {
                                //Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"), true);
                                //f.ShowDialog();
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx")))
                            {
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, path2 + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd")))
                            {
                                //Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"), true);
                                //f.ShowDialog();
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx")))
                            {
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx"));
                                ppp.ShowDialog();
                            }
                        }
                        else
                        {
                            if (System.IO.File.Exists(path + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd")))
                            {
                                //Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"), true);
                                //f.ShowDialog();
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, path + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(path + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx")))
                            {
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, path + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd")))
                            {
                                //Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"), true);
                                //f.ShowDialog();
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbmd"));
                                ppp.ShowDialog();
                            }
                            else if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx")))
                            {
                                NSBTP.NSBPT_Edit ppp = new NSBTP.NSBPT_Edit(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbtp", "nsbtx"));
                                ppp.ShowDialog();
                            }
                        }
                        break;
                    case ".nsbta":
                        if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbta", "nsbtx")))
                        {
                            NSBTA_editor a = new NSBTA_editor(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbta", "nsbtx"));
                            a.ShowDialog();
                        }
                        else if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbta", "nsbmd")))
                        {
                            NSBTA_editor a = new NSBTA_editor(dirpath + "\\" + "unpack\\" + e.Node.FullPath, dirpath + "\\" + "unpack\\" + e.Node.FullPath.Replace("nsbta", "nsbmd"));
                            a.ShowDialog();
                        }
                        break;
                    case ".nkm":
                        Form f2 = new nkm(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                        f2.ShowDialog();
                        break;
                    case ".bmg":
                            bmg f3 = new bmg(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                            f3.ShowDialog();
                            File.WriteAllBytes(dirpath + "\\" + "unpack\\" + e.Node.FullPath, f3.file_);
                        break;
                    case ".nftr":
                        /*if (e.Node.Level > 0)
                        {
                            Form f = new NFTRedit.MainForm(dirpath + "\\" + "unpack\\" + e.Node.Parent.Text + "\\" + e.Node.Text);
                            f.ShowDialog();
                        }
                        else
                        {
                            Form f = new NFTRedit.MainForm(dirpath + "\\" + "unpack\\" + e.Node.Text);
                            f.ShowDialog();
                        }*/
                        break;
                    case ".mr":
                        Form f4 = new mission(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                        f4.ShowDialog();
                        break;
                    case ".kcl":
                        if (libWiiSharp.Lz77.IsLz77Compressed(dirpath + "\\" + "unpack\\" + e.Node.FullPath))
                        {
                            libWiiSharp.Lz77 lz2 = new libWiiSharp.Lz77();
                            byte[] f9 = lz2.Decompress(System.IO.File.ReadAllBytes(dirpath + "\\" + "unpack\\" + e.Node.FullPath));
                            Stream str = new MemoryStream(f9);


                            Form f5 = new kcl(str, true);
                            f5.ShowDialog();
                        }
                        else
                        {
                            Form f = new kcl(dirpath + "\\" + "unpack\\" + e.Node.FullPath);
                            f.ShowDialog();
                        }
                        break;
                    case ".nclr":
                        nclr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        PluginInterface.NCLR c = Tinke.Imagen_NCLR.Leer(nclr);
                        Tinke.iNCLR iNCLR1 = new Tinke.iNCLR(c);
                        panel1.Controls.Clear();
                        panel1.Controls.Add(iNCLR1);
                        break;
                    case ".ncgr":
                        ncgr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        if (nclr != "" && ncgr != "")
                        {

                            PluginInterface.NCGR q = Tinke.Imagen_NCGR.Leer(ncgr);
                            PluginInterface.NCLR z = Tinke.Imagen_NCLR.Leer(nclr);

                            Tinke.iNCGR iNCGR2 = new Tinke.iNCGR(q, z);
                            panel1.Controls.Clear();
                            panel1.Controls.Add(iNCGR2);
                            iNCGR2.tilechange += new EventHandler(iNCGR2_tilechange);
                            //MKDS_Course_Editor.Pictures.NCGR nc = new Pictures.NCGR(ncgr, nclr);
                            //nc.ShowDialog();
                        }
                        break;
                    case ".nscr":
                        nscr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        if (nclr != "" && ncgr != "" && nscr != "")
                        {
                            panel1.Controls.Clear();
                            PluginInterface.NCGR w = Tinke.Imagen_NCGR.Leer(ncgr);
                            PluginInterface.NCLR z = Tinke.Imagen_NCLR.Leer(nclr);
                            PluginInterface.NSCR p2 = Tinke.Imagen_NSCR.Leer(nscr);
                            w.rahc.tileData = Tinke.Imagen_NSCR.Modificar_Tile(p2, w.rahc.tileData);
                            w.rahc.nTilesX = (ushort)(p2.section.width / 8);
                            w.rahc.nTilesY = (ushort)(p2.section.height / 8);
                            Tinke.iNCGR iNCGR3 = new Tinke.iNCGR(w, z);
                            panel1.Controls.Add(iNCGR3);
                        }
                        break;
                    case ".ncer":
                        nscr = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        if (nclr != "" && ncer != "" && ncgr != "")
                        {
                            panel1.Controls.Clear();
                            PluginInterface.NCGR w3 = Tinke.Imagen_NCGR.Leer(ncgr);
                            PluginInterface.NCLR z3 = Tinke.Imagen_NCLR.Leer(nclr);
                            PluginInterface.NCER p2_ = Tinke.Imagen_NCER.Leer(ncer);
                            Tinke.iNCER iNCGR4 = new Tinke.iNCER(p2_, w3, z3);
                            panel1.Controls.Add(iNCGR4);
                        }
                        break;
                    case ".nanr":
                        narn = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        if (nclr != "" && narn != "" && ncgr != "" && ncer != "")
                        {
                            panel1.Controls.Clear();
                            PluginInterface.NCGR w31 = Tinke.Imagen_NCGR.Leer(ncgr);
                            PluginInterface.NCLR z31 = Tinke.Imagen_NCLR.Leer(nclr);
                            PluginInterface.NANR p2_1 = Tinke.Imagen_NANR.Leer(narn);
                            PluginInterface.NCER p21 = Tinke.Imagen_NCER.Leer(ncer);
                            Tinke.iNANR iNCGR5 = new Tinke.iNANR(z31, w31, p21, p2_1);
                            panel1.Controls.Add(iNCGR5);
                        }
                        break;
                    case ".tif":
                    case ".jpg":
                    case ".bmp":
                    case ".png":
                            PictureBox pic = new PictureBox();
                            pic.Dock = DockStyle.Fill;
                            pic.ImageLocation = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                            pic.SizeMode = PictureBoxSizeMode.CenterImage;
                            panel1.Controls.Add(pic);
                        break;
                    case ".bncl":
                        bncl = dirpath + "\\" + "unpack\\" + e.Node.FullPath;
                        if (nclr != "" && ncer != "" && ncgr != "" && bncl != "")
                        {
                            BNCL fo = new BNCL(bncl, ncer, ncgr, nclr);
                            fo.ShowDialog();
                        }
                        break;
                }
            }
        }

        void iNCGR2_tilechange(object sender, EventArgs e)
        {
            Tinke.iNCGR c = (Tinke.iNCGR)sender;
            File.WriteAllBytes(ncgr, Tinke.Imagen_NCGR.Write(c.tile));
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form f = new About();
            f.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (useNDSfileID1 == -1)
            {
                if (openFileDialog1.FileName.EndsWith(".carc"))
                {
                    MKDS_Course_Editor.narc.pack(path + "\\unpack", path + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"));
                    File.WriteAllBytes(openFileDialog1.FileName, NSMBe4.ROM.LZ77_FastCompress(File.ReadAllBytes(path + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"))));
                }
                else if (openFileDialog1.FileName.EndsWith(".narc"))
                {
                    MKDS_Course_Editor.narc.pack(path + "\\unpack", openFileDialog1.FileName);
                }
            }
            else
            {
                if (dialog.getName(useNDSfileID1).EndsWith(".carc"))
                {
                    MKDS_Course_Editor.narc.pack(path + "\\unpack", path + "\\" + dialog.getName(useNDSfileID1).Replace("carc", "NARC"));
                    dialog.replace(useNDSfileID1, NSMBe4.ROM.LZ77_FastCompress(File.ReadAllBytes(path + "\\" + dialog.getName(useNDSfileID1).Replace("carc", "NARC"))));
                }
                else if (dialog.getName(useNDSfileID1).EndsWith(".narc"))
                {
                    MKDS_Course_Editor.narc.pack(path + "\\unpack", path + "\\"+dialog.getName(useNDSfileID1));
                    dialog.replace(useNDSfileID1,File.ReadAllBytes(path + "\\"+dialog.getName(useNDSfileID1)));
                }
            }
        }
        private TreeNode m_OldSelectNode;
        private void treeView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {

        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //saveFileDialog2.FileName = treeView1.SelectedNode.
            if (saveFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK
               && saveFileDialog2.FileName.Length > 0)
            {

            }
        }
        public void open()
        {

        }

        private void Form1_Shown(object sender, EventArgs e)
        {


        }

        private void panel1_SizeChanged(object sender, EventArgs e)
        {
            if (Process.GetProcessesByName("nsbmd").Length > 0)
            {
                ShowWindow(handle2, 9);
                ShowWindow(handle2, WS_MAXIMIZE);
            }
        }

        private void openTextureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog2.FileName.Length > 0)
            {
                treeView2.Nodes.Clear();
                switch (openFileDialog2.SafeFileName.Remove(0, openFileDialog2.SafeFileName.LastIndexOf(".")))
                {
                    case ".carc":
                        path2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                        System.IO.Directory.CreateDirectory(path2);
                        File.WriteAllBytes(path2 + "\\" + openFileDialog2.SafeFileName.Replace("carc", "NARC"), NSMBe4.ROM.LZ77_Decompress(File.ReadAllBytes(openFileDialog2.FileName)));
                        //lz.Decompress(openFileDialog2.FileName, path2);
                        System.IO.Directory.CreateDirectory(path2 + "\\" + "unpack");
                        narc.unpack(path2 + "\\" + openFileDialog2.SafeFileName.Replace("carc", "NARC"), path2 + "\\unpack");
                        string[] en = System.IO.Directory.GetFileSystemEntries(path2 + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                        for (int i = 0; i < en.Length; i++)
                        {
                            en[i] = en[i].Replace(path2 + "\\" + "unpack", "");
                        }
                        PopulateTreeView(treeView2, en, '\\');
                        TreeNodeCollection nc3 = treeView2.Nodes[0].Nodes;
                        treeView2.Nodes.Clear();
                        TreeNode[] tr = new TreeNode[nc3.Count];
                        nc3.CopyTo(tr, 0);
                        treeView2.Nodes.AddRange(tr);
                        foreach (TreeNode rootNode in treeView2.Nodes)
                            ParseNode(rootNode,2);
                        break;
                    case ".narc":
                        path2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MKDS temp\\" + Guid.NewGuid().ToString();
                        System.IO.Directory.CreateDirectory(path2);
                        System.IO.Directory.CreateDirectory(path2 + "\\" + "unpack");
                        System.IO.File.Copy(openFileDialog2.FileName, path2 + "\\" + openFileDialog2.SafeFileName);
                        narc.unpack(path2 + "\\" + openFileDialog2.SafeFileName.Replace("carc", "NARC"), path2 + "\\unpack");
                        string[] en2 = System.IO.Directory.GetFileSystemEntries(path2 + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                        for (int i = 0; i < en2.Length; i++)
                        {
                            en2[i] = en2[i].Replace(path2 + "\\" + "unpack", "");
                        }
                        PopulateTreeView(treeView2, en2, '\\');
                        TreeNodeCollection nc4 = treeView2.Nodes[0].Nodes;
                        treeView2.Nodes.Clear();
                        TreeNode[] tr1 = new TreeNode[nc4.Count];
                        nc4.CopyTo(tr1, 0);
                        treeView2.Nodes.AddRange(tr1);
                        foreach (TreeNode rootNode in treeView2.Nodes)
                            ParseNode(rootNode, 2);
                        break;
                }
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                saveFileDialog2.FileName = treeView1.SelectedNode.Text;
                if (saveFileDialog2.ShowDialog() == DialogResult.OK
                    && saveFileDialog2.FileName.Length > 0)
                {
                    System.IO.File.Copy(path + "\\unpack\\" + treeView1.SelectedNode.FullPath, saveFileDialog2.FileName, true);
                }
            }
        }

        private void saveFileDialog2_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void nDSBannerEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form f = new Romer.RomeR();
            f.ShowDialog();
        }

        private void decompressToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog3.FileName.Length > 0)
            {
                if (libWiiSharp.Lz77.IsLz77Compressed(openFileDialog3.FileName))
                {
                    saveFileDialog3.FileName = openFileDialog3.FileName;
                    if (saveFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                        && saveFileDialog3.FileName.Length > 0)
                    {
                        libWiiSharp.Lz77 lz2 = new libWiiSharp.Lz77();
                        byte[] f9 = lz2.Decompress(System.IO.File.ReadAllBytes(openFileDialog3.FileName));
                        System.IO.File.WriteAllBytes(saveFileDialog3.FileName, f9);
                    }
                }
                else
                {
                    MessageBox.Show("File isn't lz77 compressed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void compressToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog3.FileName.Length > 0)
            {
                if (!libWiiSharp.Lz77.IsLz77Compressed(openFileDialog3.FileName))
                {
                    saveFileDialog3.FileName = openFileDialog3.FileName;
                    if (saveFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                        && saveFileDialog3.FileName.Length > 0)
                    {
                        libWiiSharp.Lz77 lz2 = new libWiiSharp.Lz77();
                        byte[] f9 = lz2.Compress(System.IO.File.ReadAllBytes(openFileDialog3.FileName));
                        System.IO.File.WriteAllBytes(saveFileDialog3.FileName, f9);
                    }
                }
                else
                {
                    MessageBox.Show("File is lz77 compressed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void overlayDecompressToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog3.FileName.Length > 0)
            {
                try
                {
                    byte[] byt = NSMBe4.ROM.DecompressOverlay(File.ReadAllBytes(openFileDialog3.FileName));
                    
                    saveFileDialog3.FileName = openFileDialog3.FileName;
                    if (saveFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                        && saveFileDialog3.FileName.Length > 0)
                    {
                        File.WriteAllBytes(saveFileDialog3.FileName, byt);
                    }
                }
                catch
                {
                    MessageBox.Show("Error");
                }
            }
        }

        private void overlayToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void compressToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog3.FileName.Length > 0)
            {
                try
                {
                    DSDecmp.Formats.LZOvl l = new DSDecmp.Formats.LZOvl();
                    MemoryStream m = new MemoryStream(File.ReadAllBytes(openFileDialog3.FileName));
                    MemoryStream o = new MemoryStream();
                    l.Compress(m, m.Length, o);
                    saveFileDialog3.FileName = openFileDialog3.FileName;
                    if (saveFileDialog3.ShowDialog() == System.Windows.Forms.DialogResult.OK
                        && saveFileDialog3.FileName.Length > 0)
                    {
                        File.WriteAllBytes(saveFileDialog3.FileName, o.ToArray());
                    }
                }
                catch
                {
                    MessageBox.Show("Error");
                }
            }
        }

        private void exportToNSBTXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog4.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog4.FileName.Length > 0)
            {
                EndianBinaryReader er = new EndianBinaryReader(File.OpenRead(openFileDialog4.FileName), Endianness.LittleEndian);
                if (er.ReadString(Encoding.ASCII, 4) == "BMD0")
                {
                    er.ReadBytes(2);
                    if (er.ReadInt16() == 2)
                    {
                        er.ReadBytes(0xC);
                        er.BaseStream.Position = er.ReadInt32();
                        byte[] nsb = new byte[er.BaseStream.Length - er.BaseStream.Position];
                        nsb = er.ReadBytes(nsb.Length);
                        List<byte> header = new List<byte>();
                        header.AddRange(new byte[] { 0x42, 0x54, 0x58, 0x30, 0xFF, 0xFE, 0x01, 0x00 });
                        byte[] size = BitConverter.GetBytes(0x14 + nsb.Length);
                        Array.Reverse(size);
                        header.AddRange(size);
                        header.AddRange(new byte[] { 0x10, 0x00, 0x01, 0x00, 0x14, 0x00, 0x00, 0x00 });
                        header.AddRange(nsb);
                        if (saveFileDialog4.ShowDialog() == System.Windows.Forms.DialogResult.OK
                                && saveFileDialog4.FileName.Length > 0)
                        {
                            File.WriteAllBytes(saveFileDialog4.FileName, header.ToArray());
                        }
                    }
                    else
                    {
                        MessageBox.Show("error");
                    }
                }
                else
                {
                    MessageBox.Show("error");
                }
            }
        }

        private void kCLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*Form f = new SM64DSe.ModelImporter();
            f.ShowDialog();*/
            if (openFileDialog17.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog17.FileName.Length > 0)
            {
                if (saveFileDialog12.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && saveFileDialog12.FileName.Length > 0)
                {
                    KCL.Obj2Kcl k = new KCL.Obj2Kcl();
                    k.ConvertToKcl(openFileDialog17.FileName, saveFileDialog12.FileName);
                }
            }
        }


        private static void PopulateTreeView(TreeView treeView, IEnumerable<string> paths, char pathSeparator)
        {
            TreeNode lastNode = null;
            string subPathAgg;
            foreach (string path in paths)
            {
                subPathAgg = string.Empty;
                foreach (string subPath in path.Split(pathSeparator))
                {
                    subPathAgg += subPath + pathSeparator;
                    TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                    if (nodes.Length == 0)
                        if (lastNode == null)
                            lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                        else lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                    else lastNode = nodes[0];
                }
            }
        }

        private void ParseNode(TreeNode node, int tv)
        {
            if (node.Text.Contains(".") && node.Nodes.Count == 0)
            {
                node.ContextMenuStrip = contextMenuStrip3;
                switch (Path.GetExtension(node.Text).ToLower())
                {
                    case ".nsbtx":
                        node.ImageIndex = 1;
                        node.SelectedImageIndex = 1;
                        break;
                    case ".nsbmd":
                        node.ImageIndex = 2;
                        node.SelectedImageIndex = 2;
                        node.ContextMenuStrip = contextMenuStrip2;
                        break;
                    case ".nsbtp":
                    case ".nsbta":
                        node.ImageIndex = 4;
                        node.SelectedImageIndex = 4;
                        break;
                    case ".nkm":
                        node.ImageIndex = 5;
                        node.SelectedImageIndex = 5;
                        break;
                    case ".kcl":
                        node.ImageIndex = 6;
                        node.SelectedImageIndex = 6;
                        break;
                    case ".nclr":
                        node.ImageIndex = 7;
                        node.SelectedImageIndex = 7;
                        break;
                    case ".ncgr":
                        node.ImageIndex = 8;
                        node.SelectedImageIndex = 8;
                        break;
                    case ".nscr":
                        node.ImageIndex = 9;
                        node.SelectedImageIndex = 9;
                        break;
                    case ".ncer":
                        node.ImageIndex = 10;
                        node.SelectedImageIndex = 10;
                        break;
                    case ".nanr":
                        node.ImageIndex = 11;
                        node.SelectedImageIndex = 11;
                        break;
                }
                if (tv == 1)
                {
                    dirpath = path;
                }
                else { dirpath = path2; }
                if (libWiiSharp.Lz77.IsLz77Compressed(dirpath + "\\" + "unpack\\" + node.FullPath))
                {
                    node.ForeColor = Color.Blue;
                }
            }
            else
            {
                node.ImageIndex = 3;
                node.SelectedImageIndex = 3;
            }
            
            foreach (TreeNode child in node.Nodes)
                ParseNode(child, tv);

            //TODO: work goes here for DFS 
        }

        private void showTextureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(dirpath + "\\" + "unpack\\" + tree.SelectedNode.FullPath.Replace("nsbmd", "nsbtp")))
            {
                Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + tree.SelectedNode.FullPath, true);
                f.ShowDialog();
            }
            else
            {
                Form f = new MKDS_Course_Editor.NSBTX.nsbtx_(dirpath + "\\" + "unpack\\" + tree.SelectedNode.FullPath, false);
                f.ShowDialog();
            }
        }

        private void createFromMemoryDumpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("To create a ghost from a memory dump, you have to load a time trail with ghost in DeSmuME 0.9.6. When the race starts click on the pauze icon and goto: Tools->View Memory. Click on dump all and save. Then you go to the emblem edit dialog press pauze and dump the memory. When you press OK you will have to first select your ghost-memory dump and then your emblem-memory dump. Then you can save it as a staff ghost file.");
            if (openFileDialog5.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog5.FileName.Length > 0)
            {
                byte[] b = File.ReadAllBytes(openFileDialog5.FileName);
                if (openFileDialog6.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog6.FileName.Length > 0)
                {
                    byte[] c = File.ReadAllBytes(openFileDialog6.FileName);
                    List<byte> d = new List<byte>();
                    byte[] f = new byte[0x200];
                    Array.Copy(c, 0xB30A00, f, 0, 0x200);
                    byte[] g = new byte[0x30];
                    Array.Copy(b, 0x3D01C0, g, 0, 0x30);
                    byte[] h = new byte[0xDD0];
                    Array.Copy(b, 0x3D01C0 + 0x30, h, 0, 0xDD0);
                    d.AddRange(g);
                    d.AddRange(f);
                    d.AddRange(h);
                    d[2] = (byte)'D';
                    if (saveFileDialog5.ShowDialog() == System.Windows.Forms.DialogResult.OK
                        && saveFileDialog5.FileName.Length > 0)
                        {
                            File.WriteAllBytes(saveFileDialog5.FileName, d.ToArray());
                        }
                }
            }
        }

        private void sWARSWAVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog7.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog7.FileName.Length > 0)
            {
                SDAT.SWAR.ArchivoSWAR ar = SDAT.SWAR.LeerArchivo(openFileDialog7.FileName);
                SDAT.SWAV.ArchivoSWAV[] asw = SDAT.SWAR.ConvertirASWAV(ar);
                if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && folderBrowserDialog1.SelectedPath.Length > 0)
                {
                    for (int i = 0; i < asw.Length; i++)
                    {
                        SDAT.SWAV.EscribirArchivo(asw[i], folderBrowserDialog1.SelectedPath + "\\SWAV" + i.ToString("00"));
                    }
                }
            }
        }

        private void sWAVWAVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog8.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog8.FileName.Length > 0)
            {
                SDAT.SWAV.ArchivoSWAV asw = SDAT.SWAV.LeerArchivo(openFileDialog8.FileName);
                SDAT.WAV.ArchivoWAV wav = SDAT.SWAV.ConvertirAWAV(asw);
                if (saveFileDialog6.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && saveFileDialog6.FileName.Length > 0)
                {
                    SDAT.WAV.EscribirArchivo(wav, saveFileDialog6.FileName);
                }
            }
        }

        private void sTRMWAVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog9.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog9.FileName.Length > 0)
            {
                SDAT.STRM.sSTRM asw = SDAT.STRM.LeerArchivo(openFileDialog9.FileName);
                SDAT.WAV.ArchivoWAV wav = SDAT.STRM.ConvertirAWAV(asw);
                if (saveFileDialog6.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && saveFileDialog6.FileName.Length > 0)
                {
                    SDAT.WAV.EscribirArchivo(wav, saveFileDialog6.FileName);
                }
            }
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Help.ShowHelp(this, "help.chm");
        }

        private void wAVSTRMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog10.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog10.FileName.Length > 0)
            {
                STRM.sSTRM s = new STRM.sSTRM();
                s = STRM.ConvertToSTRM(WAV.Read(openFileDialog10.FileName));
                if (saveFileDialog7.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && saveFileDialog7.FileName.Length > 0)
                {
                    STRM.Write(s, saveFileDialog7.FileName);
                }
            }
        }

        private void wAVSWAVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog10.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog10.FileName.Length > 0)
            {
                SWAV.ArchivoSWAV s = new SWAV.ArchivoSWAV();
                s = SWAV.ConvertToSWAV(WAV.Read(openFileDialog10.FileName));
                if (saveFileDialog8.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && saveFileDialog8.FileName.Length > 0)
                {
                    SWAV.Write(s, saveFileDialog8.FileName);
                }
            }
        }

        private void convertToOBJToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog11.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog11.FileName.Length > 0)
            {
                Nsbmd nsbm = NsbmdLoader.LoadNsbmd(File.OpenRead(openFileDialog11.FileName));
                NsbmdGlRenderer t = new NsbmdGlRenderer();
                t.Model = nsbm.models[0];
                if (saveFileDialog9.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && saveFileDialog9.FileName.Length > 0)
                {
                    t.WriteOBJ(nsbm.models[0].Polygons[0].PolyData, saveFileDialog9.FileName);
                }
            }
        }

        private void importNSBTXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if(treeView1.SelectedNode != null)
            {
                if (openFileDialog16.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && openFileDialog16.FileName.Length > 0)
                {
                    dirpath = path;
                    File.Copy(openFileDialog16.FileName, new FileInfo(dirpath + "\\" + "unpack\\" + treeView1.SelectedNode.FullPath).DirectoryName + "\\" + openFileDialog16.SafeFileName);
                    string[] en_ = System.IO.Directory.GetFileSystemEntries(path + "\\" + "unpack", "*.*", SearchOption.AllDirectories);
                    for (int i = 0; i < en_.Length; i++)
                    {
                        en_[i] = en_[i].Replace(path + "\\" + "unpack", "");
                    }
                    treeView1.Nodes.Clear();
                    PopulateTreeView(treeView1, en_, '\\');
                    TreeNodeCollection nc3_ = treeView1.Nodes[0].Nodes;
                    treeView1.Nodes.Clear();
                    TreeNode[] tr_ = new TreeNode[nc3_.Count];
                    nc3_.CopyTo(tr_, 0);
                    treeView1.Nodes.AddRange(tr_);
                    foreach (TreeNode rootNode in treeView1.Nodes)
                        ParseNode(rootNode, 1);
                }
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                openFileDialog13.FileName = treeView1.SelectedNode.Text;
                if (openFileDialog13.ShowDialog() == DialogResult.OK
                    && openFileDialog13.FileName.Length > 0)
                {
                    System.IO.File.Copy(openFileDialog13.FileName, path + "\\unpack\\" + treeView1.SelectedNode.FullPath, true);
                }
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && saveFileDialog1.FileName.Length > 0)
            {
                switch (saveFileDialog1.FilterIndex)
                {
                    case 2:
                        //System.IO.File.WriteAllBytes(dirpath + "\\narc.exe", Properties.Resources.narctool);
                        //p.StartInfo.Arguments = "p \"" + dirpath + "\\unpack\" \""+ dirpath +"\\"+ openFileDialog1.SafeFileName.Replace("carc", "NARC") + "\"";
                        //p.StartInfo.FileName = dirpath + "\\narc.exe";
                        //p.Start();
                        //p.WaitForExit();
                        MKDS_Course_Editor.narc.pack(dirpath + "\\unpack", dirpath + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"));
                        File.WriteAllBytes(saveFileDialog1.FileName, NSMBe4.ROM.LZ77_FastCompress(File.ReadAllBytes(dirpath + "\\" + openFileDialog1.SafeFileName.Replace("carc", "NARC"))));
                        //p.StartInfo.Arguments = "c \"" + openFileDialog1.FileName.Replace("carc", "NARC") + "\" \"" + saveFileDialog1.FileName + "\"";
                        //p.Start();
                        //p.WaitForExit();
                        break;
                    case 1:
                        //System.IO.File.WriteAllBytes(dirpath + "\\narc.exe", Properties.Resources.narctool);
                        //p.StartInfo.Arguments = "p \"" + dirpath + "\\unpack\" \"" + saveFileDialog1.FileName + "\"";
                        //p.StartInfo.FileName = dirpath + "\\narc.exe";
                        //p.Start();
                        //p.WaitForExit();
                        MKDS_Course_Editor.narc.pack(dirpath + "\\unpack", saveFileDialog1.FileName);
                        break;
                }
            }
        }

        private void mIDSSEQToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog14.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog14.FileName.Length > 0)
            {
                if (saveFileDialog11.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && saveFileDialog11.FileName.Length > 0)
                {
                    sseq s = new sseq();
                    s.midiToSSEQ(openFileDialog14.FileName, saveFileDialog11.FileName);
                }
            }
        }

        private void nCLRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            nclr_e ed = new nclr_e(new Color[] { }, false, 0);
            ed.ShowDialog();
        }

        private void decompressToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openFileDialog15.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog15.FileName.Length > 0)
            {
                Arm9Editor v = new Arm9Editor(openFileDialog15.FileName);
                v.ShowDialog();
            }
        }

        private void generateCoursePictureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CoursePictureGenerator g = new CoursePictureGenerator();
            g.ShowDialog();
        }

        private void testFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BN_L.BN_L f = new BN_L.BN_L();
            f.ShowDialog();
        }

        private void openInHexeditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HexEditor h = new HexEditor(dirpath + "\\" + "unpack\\" + tree.SelectedNode.FullPath);
            h.ShowDialog();
        }

        private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.ShowDialog();
        }

        private void bCKNSBCAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog18.ShowDialog() == System.Windows.Forms.DialogResult.OK
               && openFileDialog18.FileName.Length > 0)
            {
                GCN.BCK.BCK.Bck b = GCN.BCK.BCK.readBck(openFileDialog18.FileName);
                b.ToNSBCA(Path.GetFullPath(openFileDialog18.FileName).Replace(Path.GetExtension(openFileDialog18.FileName), ".ica"));
            }
        }

        private void bMDNSBMDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog19.ShowDialog() == System.Windows.Forms.DialogResult.OK
               && openFileDialog19.FileName.Length > 0)
            {
                GCN.BMD.BMD.BModel b = GCN.BMD.BMD.loadBmd(openFileDialog19.FileName);
            }
        }

        private void courseEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog20.ShowDialog() == System.Windows.Forms.DialogResult.OK
               && openFileDialog20.FileName.Length > 0)
            {
                MKDSEditor.CourseSelector c = new MKDSEditor.CourseSelector(openFileDialog20.FileName);
                c.ShowDialog();
            }
        }

        private void nSBTPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NSBTP.Wizard w = new NSBTP.Wizard();
            w.ShowDialog();
        }

        private void bCOOBJToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog21.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog21.FileName.Length > 0)
            {
                if (saveFileDialog13.ShowDialog() == System.Windows.Forms.DialogResult.OK
                    && saveFileDialog13.FileName.Length > 0)
                {
                    GCN.BCO.BCO.Read(openFileDialog21.FileName, saveFileDialog13.FileName);
                }
            }
        }

        private void fixUVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog22.ShowDialog() == System.Windows.Forms.DialogResult.OK
                            && openFileDialog22.FileName.Length > 0)
            {
                NitroIntermediate.Helper.FixUV(openFileDialog22.FileName);
            }
        }

        private void nSBMDToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openFileDialog23.ShowDialog() == System.Windows.Forms.DialogResult.OK
                           && openFileDialog23.FileName.Length > 0)
            {
                Obj2Nsbmd on = new Obj2Nsbmd();
                on.Convert(openFileDialog23.FileName, @"C:\test.nsbmd");
            }
        }

        private void cWAVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog24.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog24.FileName.Length > 0)
            {
                _3DSExplorer.Modules.CWAVContext c = new _3DSExplorer.Modules.CWAVContext();
                c.Open(File.OpenRead(openFileDialog24.FileName));
                c.Activate(openFileDialog24.FileName, 0, null);
            }
        }

        private void editOverlaysInRomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog15.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog15.FileName.Length > 0)
            {
                OverlayEditor v = new OverlayEditor(openFileDialog15.FileName);
                v.ShowDialog();
            }
        }

		private void setFileAssociationsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Associations a = new Associations();
			a.ShowDialog();
		}



    }
    
}
